package com.example.redis.controller;

import com.example.redis.entity.User;
import com.example.redis.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

@Controller
@Api(tags = "用户控制器")
public class UserController {

    @Autowired
    IUserService userService;

    @ApiOperation("删除用户")
    @DeleteMapping(value = "/user/{id}")
    @ResponseBody
    public ResponseEntity<String> deleteByPrimaryKey(@PathVariable("id") int id) {
        userService.deleteByPrimaryKey(id);
        return ResponseEntity.ok("成功");
    }

    @ApiOperation("增加用户")
    @PostMapping(value = "/user")
    @ResponseBody
    public ResponseEntity<User> insert(User record) {
        User user = new User();
        user.setName(record.getName());
        user.setEmail(record.getEmail());
        user.setPhone(record.getPhone());
        user.setCreatetime(new Date());
        userService.insert(user);

        return ResponseEntity.ok().build();

    }

    @ApiOperation("查询用户")
    @GetMapping(value = "/user/{id}")
    @ResponseBody
    public ResponseEntity<User> selectByPrimaryKey(@PathVariable("id")int id) {
        return ResponseEntity.ok(userService.selectByPrimaryKey(id));
    }

    @ApiOperation("更新用户")
    @PutMapping(value = "/user")
    @ResponseBody
    public void updateByPrimaryKey(User record) {
        User user = userService.selectByPrimaryKey(record.getId());
        user.setName(record.getName());
        user.setEmail(record.getEmail());
        user.setPhone(record.getPhone());
        userService.updateByPrimaryKey(user);
    }

}
